package com.yuzhihao.writejvm.attributes;

import com.yuzhihao.writejvm.clazz.ClassInfo;
import com.yuzhihao.writejvm.read.Parse;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.log4j.Log4j2;

import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 *  * The LocalVariableTable attribute is an optional variable-length attribute in the attributes table of a Code attribute (§4.7.3). It may be used by debuggers to determine the value of a given local variable during the execution of a method.
 * <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.14">LocalVariableTypeTableAttribute</a>
 *
 * @author yzh
 * @since 2021年12月11日13:43:58
 */
@Data
@Log4j2
@EqualsAndHashCode(callSuper = true)
public class LocalVariableTypeTableAttribute extends Attributes {

    private int local_variable_type_table_length_u2 = 2;

    private int local_variable_type_table_length;

    private List<LocalVariable> lines = new ArrayList<>();

    public LocalVariableTypeTableAttribute(String name){
        super();
        super.setAttribute_name(name);
    }

    @Override
    public void parse(DataInputStream dis, ClassInfo ci) {
        try {
            super.attribute_length = Parse.byteToInt(super.attribute_length_u4, dis);
            this.local_variable_type_table_length = Parse.byteToInt(this.local_variable_type_table_length_u2, dis);

            int i = 0;
            while (i < this.local_variable_type_table_length){
                LocalVariable line = new LocalVariable();
                line.parse(dis,ci);
                this.lines.add(line);
                i++;
            }
        } catch (IOException e) {
            log.error(e);
        }
    }

    @Data
    @Log4j2
    public static class LocalVariable implements Parse{

        private int start_pc_u2 = 2;
        private int start_pc;

        private int length_u2 = 2;
        private int length;

        private int name_index_u2 = 2;
        private int name_index;

        private int signature_index_u2 = 2;
        private int signature_index;

        private int index_u2 = 2;
        private int index;

        @Override
        public void parse(DataInputStream dis, ClassInfo ci) {
            try {
                this.start_pc = Parse.byteToInt(this.start_pc_u2, dis);
                this.length = Parse.byteToInt(this.length_u2, dis);
                this.name_index = Parse.byteToInt(this.name_index_u2, dis);
                this.signature_index = Parse.byteToInt(this.signature_index_u2, dis);
                this.index = Parse.byteToInt(this.index_u2, dis);
            } catch (IOException e) {
                log.error(e);
            }
        }
    }

}
